package net.xiangcaowuyu.dynamicdatasource.config;

import net.xiangcaowuyu.dynamicdatasource.datasource.DynamicDataSource;
import net.xiangcaowuyu.dynamicdatasource.datasource.DynamicDataSourceContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableTransactionManagement
public class MyBatisConfig {

    private final Logger logger = LoggerFactory.getLogger(MyBatisConfig.class);

    /**
     * 数据源1
     * @return
     */
    public DataSource dynamicDataSourceOne( ) {
        return     DataSourceBuilder
                .create()
                .url("jdbc:mysql://localhost:3306/dynamic_datasource_one?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&allowMultiQueries=true")
                .username("root")
                .password("123456")
                .driverClassName("com.mysql.jdbc.Driver")
                .build();
    }

    /**
     * 数据源2
     * @return
     */
    public DataSource dynamicDataSourceTwo() {
        return     DataSourceBuilder
                .create()
                .url("jdbc:mysql://localhost:3306/dynamic_datasource_two?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&allowMultiQueries=true")
                .username("root")
                .password("123456")
                .driverClassName("com.mysql.jdbc.Driver")
                .build();
    }

    @Bean("dynamicDataSource")
    public DataSource dynamicDataSource() {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        DataSource dynamicDataSourceOne = dynamicDataSourceOne();
        DataSource dynamicDataSourceTwo = dynamicDataSourceTwo();
        Map<Object,Object> dynamicDataSourceMap = new HashMap<>();
        dynamicDataSourceMap.put("dynamicDataSourceOne",dynamicDataSourceOne);
        dynamicDataSourceMap.put("dynamicDataSourceTwo",dynamicDataSourceTwo);
        DynamicDataSourceContextHolder.addDataSourceKeys(dynamicDataSourceMap.keySet());
        dynamicDataSource.setTargetDataSources(dynamicDataSourceMap);
        //必须执行此操作，才会重新初始化AbstractRoutingDataSource 中的 resolvedDataSources，也只有这样，动态切换才会起效
        dynamicDataSource.afterPropertiesSet();
        return dynamicDataSource;
    }

}
